package com.example.guardian.home;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.guardian.R;
import com.example.guardian.myadapter.TCase;
import com.example.guardian.myadapter.T_CaseAdapter;
import com.example.guardian.myadapter.note_adapter;
import com.example.guardian.myadapter.result_adapter;
import com.example.guardian.network.PostImage;
import com.example.guardian.network.PostKeywords;
import com.yinglan.scrolllayout.ScrollLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class NoteActivity extends AppCompatActivity {

    private ListView NlistView;

    private List<TCase> tNCaseList = new ArrayList<>();
    private List<ArrayList<String>> kind_list = new ArrayList<ArrayList<String>>();

    private T_CaseAdapter TN_adapter = new T_CaseAdapter(NoteActivity.this, tNCaseList);
    private note_adapter note_adapter;

    private String kind;
    private String prevent;
    private List relative_kind_list = new ArrayList<String>();
    private List measures_list = new ArrayList<String>();

    String pic_path = "";//图片位置

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_note);
        Context appContext = getApplicationContext();
        ActionBar actionBar = getSupportActionBar();
        Button note_search_btn = (Button) findViewById(R.id.note_search);
        EditText note_search_edittext = (EditText) findViewById(R.id.search_note);
        ScrollLayout scrollLayout = findViewById(R.id.scroll_down_layout);

        if (actionBar != null) {
            actionBar.hide();
        }
        Button back_button = findViewById(R.id.note_back_btn);

        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NoteActivity.this.finish();
            }
        });
        TextView kind_name = findViewById(R.id.kind_name);
        TextView kind_target = findViewById(R.id.target_people);
        TextView fomularr = findViewById(R.id.formula);
        TextView prev = findViewById(R.id.prevent);

        GridView result = (GridView) findViewById(R.id.CR_gridview) ;
        note_adapter = new note_adapter(kind_list,NoteActivity.this);

        this.NlistView = (ListView) findViewById(R.id.N_List_view);

        ImageButton choseImage = findViewById(R.id.note_photo);

        choseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(NoteActivity.this,
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        2);
                Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, ChatActivity.ActivityRequestCode.SHOW_MAP_DEPOT);
            }

        });


        //ListView item的展开事件
        TN_adapter.setOnItemSpreadClickListener(new T_CaseAdapter.onItemSpreadListener() {
            @Override
            public void onSpreadClick(int i) {
                TCase t_item = tNCaseList.get(i);
                AlertDialog.Builder builder = new AlertDialog.Builder(NoteActivity.this);
                builder.setTitle(t_item.getCase_name());
                builder.setMessage(t_item.getCase_content());
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
            }
        });

        ;

        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(NoteActivity.this);
                builder.setTitle("防范措施");
                builder.setMessage(prevent);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();

            }
        });

        note_search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tNCaseList.clear();
                kind_list.clear();
                String input_words = note_search_edittext.getText().toString();
                if(input_words.isEmpty()){
                    Toast.makeText(getApplicationContext(),"请您输入内容",Toast.LENGTH_SHORT).show();
                }else{
                    PostKeywords.sendOkHttpRequest("http://124.220.154.99:5000/notes_select",input_words,new okhttp3.Callback() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            //得到服务器返回的具体内容
                            String responseData = response.body().string();
                            parseDiffJson(responseData);

                            //initTCase();
                            showResponse(responseData);
                        }

                        @Override
                        public void onFailure(Call call, IOException e) {
                            //在这里对异常数据进行处理
                        }

                        private void showResponse(final String response) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(response.isEmpty()){
                                        Toast.makeText(getApplicationContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                                    }else {
                                            if (kind_list.isEmpty()) {
                                                AlertDialog.Builder builder = new AlertDialog.Builder(NoteActivity.this);
                                                builder.setTitle("暂时安全");
                                                //builder.setMessage("暂时安全");
                                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                                builder.show();

                                                NlistView.setAdapter(TN_adapter);
                                                result.setAdapter(note_adapter);
                                                setHeight.setGridViewHeight(appContext, result);
                                                setHeight.setListViewHeight(NlistView);
                                                prev.setText("");
                                                scrollLayout.setToExit();
                                            } else {

                                        NlistView.setAdapter(TN_adapter);
                                        result.setAdapter(note_adapter);
                                        setHeight.setGridViewHeight(appContext, result);
                                        setHeight.setListViewHeight(NlistView);
                                        kind_name.setText(kind);
                                        Log.e("1",kind);
                                        prev.setText(prevent);
                                        scrollLayout.setToOpen();


                                    }
                                }
                                }
                            });
                        }
                    });

                }

            }
        });


    }
    //选择图片
    public interface ActivityRequestCode {
        public static final int SHOW_MAP_DEPOT = 1; //显示Android自带图库，用于选择用户自己的图片
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == ChatActivity.ActivityRequestCode.SHOW_MAP_DEPOT
                    && resultCode == Activity.RESULT_OK)
                showYourPic(data);
        }
    }

    private void showYourPic(Intent data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        if (picturePath.equals(""))
            return;
        pic_path = picturePath; // 保存所添加的图片的路径
        returnwords(pic_path);
    }

    public void returnwords(String pic_path) {
        EditText words = findViewById(R.id.search_note);
        if(pic_path.isEmpty()){
            Toast.makeText(getApplicationContext(),"请您选择图片",Toast.LENGTH_SHORT).show();
        }else{
            PostImage.sendOkHttpRequest("http://124.220.154.99:5000/images_select",pic_path,new okhttp3.Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //得到服务器返回的具体内容
                    String responseData = response.body().string();
                    showResponse(responseData);
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    //在这里对异常数据进行处理
                }

                private void showResponse(final String response) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(response.isEmpty()){
                                Toast.makeText(getApplicationContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                            }else {
                                words.setText(response);
                            }
                        }
                    });
                }
            });

        }

    }

    private void initTCase(String Kind_name,String Case_name,String Case_content) {
        TCase tcase = new TCase(Kind_name,Case_name, Case_content);
        tNCaseList.add(tcase);
    }

    //解析JSON
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void parseDiffJson(String json) {
        try {
            JSONArray jsonArray = new JSONArray(json);
            List case_lst = new ArrayList();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                //取出word
                String word = jsonObject.getString("word");
                //取出kind列表
                JSONArray kinds = jsonObject.getJSONArray("kind");
                //Log.e("Json_word", word);
                //对kind列表进行操作
                for (int k = 0; k < kinds.length(); k++) {
                    JSONObject jsonObject_kind = (JSONObject) kinds.get(k);
                    //取出kind的name
                    kind = jsonObject_kind.getString("name");
                    //取出kind的measure
                    prevent = jsonObject_kind.getString("name")+":"+jsonObject_kind.getString("measure");
                    if(relative_kind_list.contains(kind) == false) {
                        relative_kind_list.add(kind);
                    }
                    if(measures_list.contains(prevent) == false) {
                        measures_list.add(prevent);
                    }
                    List small_kind_List = new ArrayList<String>();
                    Log.e("2", kind_list.toString() );
                    //取出official_case列表
                    JSONArray note_case = jsonObject_kind.getJSONArray("case");
                    /*Log.e("Json_kind_name", kind_name);
                    Log.e("Json_kind_measure", kind_measure);
                    Log.e("Json_kind_feature", kind_feature);*/
                    for (int o = 0; o < note_case.length(); o++) {
                        List case_list = new ArrayList<String>();
                        JSONObject jsonObject_official_case = (JSONObject) note_case.get(o);
                        //取出短信案例的内容
                        String case_content = jsonObject_official_case.getString("m.name");
                        case_list.add(kind);
                        case_list.add(case_content);
                        if(kind_list.contains(case_list) == false) {
                            kind_list.add((ArrayList<String>) case_list);
                        }
                        //Log.e("Json_kind_name", kind_name);
                        if(case_lst.contains(case_content) == false) {

                            case_lst.add(case_content);
                        }


                    }
                }
            }
            kind = "";
            prevent = "";
            for (int i = 0; i < relative_kind_list.size(); i++) {
                kind = kind+relative_kind_list.get(i)+" ";
                prevent = prevent+measures_list.get(i)+"\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}